(function () {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:ueditor
     * @description
     * # ueditor 
     */
    angular.module('webApp')
        // .run(["$templateCache", "dataService",
        //     function($templateCache, dataService) {
        //         var tplName = "views/directives.imgcc.html";
        //         dataService.tpl(tplName).then(function(html) {
        //             $templateCache.put(tplName, html);
        //         });
        //     }
        // ])
        .directive('wxueditor', function () {
            var ueditor;
            return {
                restrict: 'E',
                require: 'ngModel',
                template: '<div><div id="{{uid}}" class="ueditor" style="width:{{width}}px;height:{{height}}px;" ng-model="myUeditor" config="config" ></div><wx-gzh-url-attachment id="{{uid}}uploadattach" owner-id="attachs" dhf-ng-model="attchUrl" xtype="mid" mult="false" title="添加图片" use-type="png,jpeg,gif,jpg,JPG,PNG,JPEG,GIF" wxappid="wxappid"  setback="addimgurl(attach)" tabtype="1" style="display:none;"></wx-gzh-url-attachment> <wxapplet id="{{uid}}wxapplet" callback="appletback(attach)"  wxgzhappid="wxappid"  style="display:none;"></wxapplet></div>',
                scope: {
                    item: "=", //商品数据
                    ngModel: "=",
                    uid: "@",
                    width: "@",
                    height: "@",
                    wxappid: "=",
                    // width: "@",
                },
                controller: ['$scope', '$rootScope', 'dataService', '$timeout', function ($scope, $rootScope, dataService, $timeout) {
                    var lang = window.localStorage.lang || 'cn';
                    lang = lang == 'cn' ? 'zh-cn' : lang;
                    $scope.width = $scope.width || 750;
                    $scope.height = $scope.height || 550;
                    $scope.config = {
                        lang: lang,
                        initialFrameWidth: "500px",
                        autoFloatEnabled: false,
                        toolbars: [
                            ["undo", "redo", "|", "fontsize", "blockquote", "|", "removeformat", "formatmatch", "|", "link", "emotion", "spechars", "superscript", "subscript", "|", "PastePlain", "directionalityltr", "directionalityrtl", "|", 'touppercase', 'tolowercase',],
                            ["bold", "italic", "underline", "forecolor", "shadowcolor", "backcolor", "|", "indent", "lineheight", 'letterspacing', 'outpadding', "rowspacingtop", "rowspacingbottom", "|", "justifyleft", "justifycenter", "justifyright", "justifyjustify",],
                            ["insertorderedlist", "insertunorderedlist", "|", "autotypeset", "insertvideo", "music", 'background', 'insertimage', "horizontal", "searchreplace", "|", "source",]
                        ],

                        zIndex: 0,
                        charset: "utf-8",
                        textarea: "content",
                        initialStyle: "",
                        autoClearEmptyNode: !1,
                        enableAutoSave: !1,
                        saveInterval: 5e6,
                        imagePopup: !0,
                        emotionLocalization: !0,
                        insertorderedlist: {
                            decimal: "",
                            "lower-alpha": "",
                            "lower-roman": "",
                            "upper-alpha": "",
                            "upper-roman": "",
                            "cjk-ideographic": "一、二、三、",
                            "lower-greek": "α,β,γ,δ"
                        },
                        insertunorderedlist: {
                            circle: "",
                            disc: "",
                            square: ""
                        },
                        listDefaultPaddingLeft: "30",
                        maxListLevel: -1,
                        autoTransWordToList: !0,
                        fontfamily: [{
                            label: "",
                            name: "yahei",
                            val: "微软雅黑"
                        }, {
                            label: "",
                            name: "songti",
                            val: "宋体,SimSun"
                        }, {
                            label: "",
                            name: "kaiti",
                            val: "楷体,楷体_GB2312,SimKai"
                        }, {
                            label: "",
                            name: "heiti",
                            val: "黑体,SimHei"
                        }, {
                            label: "",
                            name: "lishu",
                            val: "隶书,SimLi"
                        }, {
                            label: "",
                            name: "arial",
                            val: "arial,helvetica,sans-serif"
                        }],
                        fontsize: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 24, 28, 32, 36],
                        letterspacing: [0, 0.5, 1, 1.5, 2, 3, 4, 5],
                        enableContextMenu: !0,
                        elementPathEnabled: !1,
                        wordCount: !1,
                        removeFormatTags: "a,b,big,code,del,dfn,em,font,i,section,blockquote,pre,fieldset,ins,kbd,q,samp,small,span,label,strike,strong,sub,sup,tt,u,var",
                        removeFormatAttributes: "class,style,lang,width,accuse,height,align,hspace,valign,data-width,data-brushtype,opacity,border,title,placeholder",
                        maxUndoCount: 50,
                        autoHeightEnabled: !1,
                        scaleEnabled: !1,
                        imageScaleEnabled: !1,
                        autotypeset: {
                            mergeEmptyline: !0,
                            removeClass: !1,
                            removeEmptyline: !1,
                            textAlign: !1,
                            imageBlockLine: !1,
                            pasteFilter: !1,
                            clearFontSize: !1,
                            clearFontFamily: !1,
                            removeEmptyNode: !1,
                            indent: !1,
                            indentValue: "2em",
                            bdc2sb: !1,
                            tobdc: !1
                        },
                        catchRemoteImageEnable: true
                    };

                    $rootScope.$on('event:wx-ueditor-add-content', function (event, data) {
                        // console.error("收到消息：", data,$scope.uid);
                        if (data.content && data.uid == $scope.uid) {
                            execCommand(data.content);
                        }
                    });

                    $timeout(function () {
                        ueditor = UE.getEditor($scope.uid);
                    }, 3000);

                    $scope.attachVideoBack = function (attach) {
                        // ueditor.setContent('<a cpath="' + attach + '" atype="video" ctype="video" >　 <video width="400" height="300" src="' + attach + '" controls="controls"></video></a>', true);
                        execCommand('<a cpath="' + attach + '" atype="video" ctype="video" >　 <video width="100%" height="300" src="' + attach + '" controls="controls"></video></a>');
                    }

                    //t添加 图片
                    $scope.attachBack = function (attach) {
                        console.log("attach:", attach, ueditor);

                        var stype = $scope.getSuffix(attach);

                        var path = '<img data-s="300,640" data-type="' + stype + '" src="' + attach + '" data-copyright="0" style="" class="" data-ratio="0.5803571428571429" data-w="448" ';
                        if ($scope.cicui == 0) {
                            path += ' />';
                        }

                        var pth = '<img data-s="300,640" data-type="' + stype + '" src="' + attach + '" data-copyright="0" style="" class="" data-ratio="0.5803571428571429" data-w="448">';

                        // 把内容追加到编辑器中
                        // ueditor.setContent(pth, true);
                        execCommand(pth);

                    }


                    $scope.addimgurl = function (attach) {
                        console.error("path", attach);
                        if (attach) {
                            var stype = $scope.getSuffix(attach);
                            var pth = '<img data-s="300,640" data-type="' + stype + '" src="' + attach + '" data-w="750" height="1334" data-copyright="0" style="" class="" data-ratio="0.5803571428571429" data-w="448" >';

                            // var pth = '<img class="" data-ratio="1.7786666666666666" data-type="' + stype + '" data-w="750" height="1334" data-src="' + attach + '" src="' + attach + '" style="width: 677px !important; height: auto !important; visibility: visible !important;"  crossorigin="anonymous" data-fail="0">';
                            execCommand(pth);
                            // showPop(attach);
                        }
                    }

                    $scope.appletback = function (attach) {
                        var path;
                        if (attach.wximg) {
                            var stype = $scope.getSuffix(attach.wximg);
                            path = '<p><a class="weapp_image_link" data-miniprogram-appid="' + attach.wxappid + '" data-miniprogram-path="' + attach.path + '" data-miniprogram-nickname="' + attach.wxappname + '" href=""><img data-s="300,640" src="' + attach.wximg + '" data-type="jpeg" class="" data-ratio="1" data-w="617"  width="260" height="200" ></a></p>';
                            //p = '<p><a class="weapp_image_link" data-miniprogram-appid="{appid}" data-miniprogram-path="{path}" data-miniprogram-nickname="{nickname}" href="">' + p + "</a></p>"

                        } else {
                            path = '<a class="weapp_text_link" data-miniprogram-appid="' + attach.wxappid + '" data-miniprogram-path="' + attach.path + '" data-miniprogram-nickname="' + attach.wxappname + '" href="" >' + attach.title + '</a>';
                        }

                        if (attach.title) {
                            path = '<a class="weapp_text_link" data-miniprogram-appid="' + attach.wxappid + '" data-miniprogram-path="' + attach.path + '" data-miniprogram-nickname="' + attach.nick_name + '" href="">' + attach.title + '</a>';
                        }
                        execCommand(path);
                    }


                    //获取文件后缀
                    $scope.getSuffix = function (attach) {
                        //根据.f分割
                        var one = attach.split(".");
                        //获取数组中最后一个，即文件名
                        var two = one[one.length - 1];

                        return two;
                    }

                    //返回连接url
                    $scope.setpath = function (path, ctype, cid, cover) {
                        // console.error("选择path", ueditor, path, ctype, cid);
                        // ueditor.selection.getRange().select();
                        if (ueditor.selection.getStartElementPath()[0].tagName == "A") {
                            var obj = {
                                'href': path,
                                'target': "_blank",
                                'ctype': ctype,
                                'cpath': path,
                                'cid': cid,
                            }
                            ueditor.execCommand('link', UE.utils.clearEmptyAttrs(obj));
                        } else {
                            if (ctype == "video") {
                                execCommand('<a cpath="' + path + '" atype="video" ctype="video" cover="' + cover + '"> 　<video width="100%" height="300" src="' + path + '" controls="controls"></video></a>');
                            } else {
                                //高亮后，才能获取到选中文本，当选中字失去焦点的情况下是获取不到的选中文本的
                                ueditor.selection.getRange().applyInlineStyle("a", { "href": path, "target": "_blank", "cpath": path, "ctype": ctype, "cid": cid });
                            }
                        }

                        // ueditor.setContent('', true); //必须执行这一行，否则代码编辑不生效
                    }

                    function execCommand(html) {
                        try {
                            $timeout(function () {
                                ueditor.focus();
                                ueditor.execCommand('inserthtml', html, !0);
                                $scope.ngModel = ueditor.getContent();
                            });
                        } catch (e) {
                            console.error("e", e);
                        }
                    }


                    //添加一个按钮
                    UE.registerUI('attachment wxapplet video map', function (editor, uiName) {
                        // console.error("ui",uiName);
                        toolBarInit(editor);
                        //注册按钮执行时的command命令，使用命令默认就会带有回退操作
                        editor.registerCommand(uiName, {
                            execCommand: function () {
                                // alert('execCommand:' + uiName);
                                ueditor = editor;
                                // console.error("按钮点击：", $scope.uid + 'uploadattach');

                                if (uiName == "attachment") {
                                    angular.element('#' + $scope.uid + 'uploadattach a').triggerHandler('click');
                                } else if (uiName == "wxapplet") {
                                    angular.element('#' + $scope.uid + 'wxapplet a').triggerHandler('click')
                                } else if (uiName == "map") {
                                    // ueditor.setContent('<a ctype="map"><img src="https://img.alicdn.com/imgextra/i2/20841398/TB2XjX0XoEIL1JjSZFFXXc5kVXa-20841398.jpg" ctype="map"/></a>', true);
                                    execCommand('<a ctype="map"><img src="https://img.alicdn.com/imgextra/i2/20841398/TB2XjX0XoEIL1JjSZFFXXc5kVXa-20841398.jpg" ctype="map"/></a>');
                                } else if (uiName == "video") {
                                    angular.element('#' + $scope.uid + 'uploadVideo a').triggerHandler('click')
                                }
                            }
                        });
                        var btn1 = {
                            name: "",
                            cssRules: ""
                        }
                        if (uiName == "attachment") {
                            btn1.name = "添加图片",
                                btn1.cssRules = "background-position: -380px 0px;"
                        } else if (uiName == "wxapplet") {
                            btn1.name = "添加小程序",
                                btn1.cssRules = "background-position: -500px 0px;"
                        } else if (uiName == "map") {
                            btn1.name = "添加地图",
                                btn1.cssRules = "background-position: -40px -40px;"
                        } else if (uiName == "video") {
                            btn1.name = "添加视频",
                                btn1.cssRules = "background-position: -320px -20px;"
                        }
                        //创建一个button
                        var btn = new UE.ui.Button({
                            //按钮的名字
                            name: btn1.name,
                            //提示
                            title: btn1.name,
                            //需要添加的额外样式，指定icon图标，这里默认使用一个重复的icon
                            cssRules: btn1.cssRules,
                            //点击时执行的命令
                            onclick: function () {
                                //这里可以不用执行命令,做你自己的操作也可
                                editor.execCommand(uiName);
                            }
                        });

                        return btn;
                    }

                        /*index 指定添加到工具栏上的那个位置，默认时追加到最后,editorId 指定这个UI是那个编辑器实例上的，默认是页面上所有的编辑器都会添加这个按钮*/
                    );

                    function toolBarInit(ueditor) {
                        var ue = ueditor;
                        ue.addListener('afterSelectionChange', function (editor) {
                            if (ue.hasContents()) { //有内容
                                $(ue.body).removeClass("indicate");
                            } else {
                                $(ue.body).addClass("indicate");
                            }
                        });
                        ue.addListener("ready", function () {
                            clearselectline();
                            $(ue.body).delegate('.dhfEditor', 'click', function (event) {
                                if (event.stopPropagation) {
                                    event.stopPropagation();
                                } else {
                                    event.cancelBubble = true;
                                }
                                clearselectline();
                                $(this).addClass("checkSelected");
                                // 加载素材操作工具条
                                materialOperation($(this));
                            });

                            // 当点击照片的时候，跳转到图库列表，并且点击的时候可以替换
                            $(ue.body).delegate('img', 'click', function (event) {
                                clearselectline();
                                if (event.stopPropagation) {
                                    event.stopPropagation();
                                } else {
                                    event.cancelBubble = true;
                                }
                                $(this).parent().addClass("checkSelected");
                                // 加载素材操作工具条
                                materialOperation($(this));
                            })
                            $(ue.window).scroll(function () {
                                clearselectline();
                                $(".material-operation-tools").remove();
                                $("[id*=collorpicker_]").hide();
                            })
                            $(ue.body).click(function (event) {
                                clearselectline();
                                $(".material-operation-tools").remove();
                                $("[id*=collorpicker_]").hide();
                            });

                        });

                        function clearselectline() {
                            $(ue.body).find(".checkSelected").removeClass("checkSelected");
                            $("menu").remove();
                            $(".material-operation-tools").remove();
                            $("[id*=collorpicker_]").hide();
                            //复制插件的隐藏
                            $("#global-zeroclipboard-html-bridge").css({
                                top: "-100px",
                                // left: $(".main-tools").position().left + 10
                            }).attr({
                                statsmark: "复制全文",
                                statstype: "3"
                            })
                        }

                        function materialOperation(material) {
                            material.ueditorToolsBar(ue);
                        }

                    };

                    // $('body').off('openAurl').on('openAurl', function(e, data) {
                    //     $('#' + $scope.uid + 'wxapplet a').click();
                    // });

                }],
                link: function (scope, element, attrs, ctrl) {
                    scope.$watch('myUeditor', function (newValue, oldValue, scope) {
                        ctrl.$setViewValue(newValue);
                    });

                    ctrl.$render = function () {
                        scope.myUeditor = (ctrl.$isEmpty(ctrl.$viewValue) ? "" : ctrl.$viewValue);
                    };

                }
            }
        })
        .directive('automaticExecutions', function () {
            var ueditor;
            return {
                restrict: 'E',
                require: 'ngModel',
                template: "<span ng-if='value==2'><a href='javascript:;' class='sui-btn' ng-click='save(1)'><i class='fa fa-close' aria-hidden='true'></i>{{title}}</a></span><span ng-if='value==1'><a href='javascript:;' class='sui-btn btn-success' ng-click='save(2)'><i class='fa fa-check' aria-hidden='true'></i>{{title}}</a></span>",
                scope: {
                    appid: "=",
                    ngModel: "=",
                    title: "@",
                    keyname: "@",
                    // width: "@",
                },
                controller: ['$scope', '$rootScope', 'dataService', '$timeout', 'helper', function ($scope, $rootScope, dataService, $timeout, helper) {
                    $scope.init = function () {
                        var type = 0;
                        var data = {
                            appid: $scope.appid,
                            // store_id: $rootScope.store_id,
                            name: $scope.keyname,
                        }
                        return dataService.wxappOne(data).then(function (list) {
                            if (list) {
                                $scope.ngModel = $scope.value = list.value;
                                $scope.addType = 1;
                            } else {
                                $scope.ngModel = $scope.value = 2;
                            }
                            // console.error("1111111111111111111111111", $scope.ngModel);
                        });
                    }

                    $scope.save = function (value) {
                        var config = {
                            store_id: $rootScope.store_id,
                            app_id: $scope.appid,
                            name: $scope.keyname,
                            value: value,
                            types: "config",
                        };
                        var post = $scope.addType ? "wxappUpdate" : "wxappAdd";
                        dataService[post](config).then(function (list) {
                            if (list.app_id) {
                                $scope.value = $scope.ngModel = value;
                                helper.myAlert("设置成功！");
                                $scope.init();
                            }
                        });
                    }
                    $scope.init();
                }],
                link: function (scope, element, attrs, ctrl) {


                }
            }
        })
    // .directive('automaticExecution', ['dataService', '$compile', function(dataService, $compile) {
    //     return {
    //         restrict: 'E',
    //         replace: true,
    //         scope: {
    //             // appId: "=",
    //             title: "@",
    //             keyName: "@",
    //         },
    //         template: "<span ng-show='value'><a href='javascript:;' class='sui-btn btn-success' ng-click='save(1)'> {{title|translate}}</a></span><span ng-show='!value'><a href='javascript:;' class='sui-btn btn-danger' ng-click='save(0)'> {{title|translate}}</a></span>",
    //         // templateUrl: "views/directives.importexcel.html",
    //         controller: ['$templateCache', '$rootScope', '$scope', '$timeout', 'sku', 'helper', 'ERP_CONFIG', '$window', 'sessionService', '$filter', function($templateCache, $rootScope, $scope, $timeout, sku, helper, ERP_CONFIG, $window, sessionService, $filter) {
    //             $scope.init = function() {
    //                 //点击升级的时候 保存这个值，取消的时候，取消 
    //                 // CONFIG-UPGRADE upgrade
    //                 var type = 0;
    //                 var data = {
    //                     appid: $scope.appId,
    //                     store_id: $rootScope.store_id,
    //                     name: $scope.keyName,
    //                 }
    //                 return dataService.wxappOne(data).then(function(list) {
    //                     if (list && list.value) {
    //                         type = list.value;
    //                     }

    //                     $scope.addType = $scope.value = type;
    //                 });
    //             }

    //             function save(value) {
    //                 var config = {
    //                     // keyName: "CONFIG-MENUBAR",
    //                     store_id: $rootScope.store_id,
    //                     app_id: $scope.appId,
    //                     name: keyName,
    //                     value: value,
    //                     types: "config",
    //                 };

    //                 var post = $scope.addType ? "wxappUpdate" : "wxappAdd";

    //                 dataService[post](saveData).then(function(list) {
    //                     if (list.app_id) {
    //                         helper.myAlert("success");
    //                     }
    //                 });
    //             }


    //         }],
    //         link: function(scope, element, attrs, ctrl) {

    //         }
    //     }
    // }])
})();